import axios from "axios";
import {ElMessage} from "element-plus";
import {jwtDecode} from "jwt-decode";

const authItemName="access_token"
const defaultFailure=(message,code,url)=>{
    console.warn(`错误地址:${url}错误代码:${code}错误信息:${message}`)
    ElMessage.warning(message)
}
const defaultError=(err)=>{
    console.error(`错误信息:${err}`)
    ElMessage.warning("发生了一些错误，请联系管理员")
}

function accessHeader(){
    return takeAccessToken() ? {
        'Authorization':`Bearer ${takeAccessToken()}`
} : {}
}
function storeAccessToken(token,remember,expire){
    const authObj={token:token,expire:expire}
    const str=JSON.stringify(authObj)
    if(remember){
        localStorage.setItem(authItemName,str)
    }else{
        sessionStorage.setItem(authItemName,str)
    }
}
function deleteAccessToken(){
    localStorage.removeItem(authItemName)
    sessionStorage.removeItem(authItemName)
}
function internalPost(url,data,header,success,failure,error=defaultError){
    console.log(data)
    axios.post(url,data,{headers:header}).then(({data})=>{
        if(data.code===200){
            success(data.data)
        }else{
            failure(data.message,data.code,data.url)
        }
    }).catch(err=>error(err))
}
function internalPut(url,data,header,success,failure,error=defaultError){
    axios.put(url,data,{headers:header}).then(({data})=>{
        if(data.code===200){
            success(data.data)
        }else{
            failure(data.message,data.code,data.url)
        }
    }).catch(err=>error(err))
}

function internalGet(url, header, success, failure, error = defaultError) {
    axios.get(url, { headers: header }).then(({ data }) => {
        console.log("响应的数据内容:", JSON.stringify(data, null, 2)); // 检查 data 的结构

        // 判断 data.code 是否为 200，且根据结构提取内容
        if (data.code === 200) {
            // 提取内容，优先使用 data.data，如果 data.data 不存在则使用 data 本身
            const content = data.data || data;
            success(content);
        } else {
            console.log("错误数据内容:", data);
            // 为 message、code、url 设置默认值，以防为 undefined
            failure(
                data.message || "未知错误信息",
                data.code || "未知错误代码",
                data.url || url
            );
        }
    }).catch(err => {
        console.error("请求错误:", err); // 捕获错误信息
        error(err); // 调用 error 回调
    });
}

function internalDelete(url,header,success,failure,error=defaultError){
    axios.delete(url,{headers:header}).then(({data})=>{
        if(data.code===200){
            success(data.data)
        }else{
            failure(data.message,data.code,data.url)
        }
    }).catch(err=>error(err))
}


function login(username,password,remember,success,failure=defaultFailure){
    internalPost("/api/auth/login",{
        username: username,
        password: password,
    },
        {
        "Content-Type":"application/x-www-form-urlencoded"
    },
        (data)=>{
        storeAccessToken(data.token,remember,data.expire)
        ElMessage.success(`登录成功，欢迎${data.username}登录该论坛`)
            success(data)
        },failure)
}
function put(url,data,success,failure=defaultFailure){
    internalPut(url,data,accessHeader(),success,failure)
}
function get(url,success,failure=defaultFailure){
    internalGet(url,accessHeader(),success,failure)
}
function post(url,data,success,failure=defaultFailure){
    internalPost(url,data,accessHeader(),success,failure)
}

function performDelete(url, success, failure = defaultFailure) {
    internalDelete(url, accessHeader(), success, failure);
}
function unauthorized(){
    return !takeAccessToken()
}

function logout(success,failure=defaultFailure){
    get("/api/auth/logout",()=>{
        deleteAccessToken()
        ElMessage(`退出登录成功，等候您的下次登录哦`)
        success()
    },failure)
}
function proFileSet(data,success,failure=defaultFailure){
    internalPost("/api/auth/home-alert",{
            id:data.id,
            img:data.img,
            name: data.name,
            birth: data.birth,
            sex:data.sex,
            dataAccessible : !!data.dataAccessible
        },
        {
            "Content-Type": "application/json", // 使用 JSON 格式
        },
        (data)=>{
            ElMessage.success(`修改成功`)
            success(data)
        },failure)

}


function decodedAccessToken() {
             // 直接调用 jwtDecode
    return jwtDecode(takeAccessToken());
}
function takeAccessToken(){
    const str=localStorage.getItem(authItemName)||sessionStorage.getItem(authItemName)
    if(!str){
        return null
    }
    const authObj=JSON.parse(str)
    if(authObj.expire<=new Date()){
        deleteAccessToken()
        ElMessage("登录信息已过期，请重新登录")
        return null
    }return authObj.token
}
export {login,logout,get,post,unauthorized,proFileSet,decodedAccessToken,performDelete,put}